const Koa = require('koa')
const consola = require('consola')
const {
  Nuxt,
  Builder
} = require('nuxt')


// //引入依赖
import mongoose from 'mongoose';
import bodyParser from 'koa-bodyparser';
import session from 'koa-generic-session';
import Redis from 'koa-redis';
//美化json
import json from 'koa-json';

//引入数据库相关
import dbConfig from './dbs/config';
import passport from './interface/utils/passport';

//引入接口
import users from './interface/users';
import geo from './interface/geo';



const app = new Koa()

//对cookies加密
app.keys = ['meituan', 'secret'];

//信任代理头字段
app.proxy = true;

//配置session，将redis数据库的用户数据存入session
app.use(session({
  key: 'meituan',
  prefix: 'meituan:uid',
  store: new Redis()
}));

//拓展类型
app.use(bodyParser({
  extendTypes: ['json', 'form', 'text']
}));

//美化/格式化json
app.use(json());

//连接数据库
mongoose.set('useCreateIndex', true);
mongoose.connect(dbConfig.dbs, {
  useNewUrlParser: true
});

//登录验证
app.use(passport.initialize());
app.use(passport.session());



// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = app.env !== 'production'

async function start() {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  const {
    host = process.env.HOST || '127.0.0.1',
      port = process.env.PORT || 3000
  } = nuxt.options.server

  await nuxt.ready()
  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }


  //注册引入的接口
  //报错！！！！！！
  //记得allowedMethods()调用执行加()
  //引入user接口路由表
  app.use(users.routes()).use(users.allowedMethods());
  app.use(geo.routes()).use(geo.allowedMethods());


  app.use((ctx) => {
    ctx.status = 200
    ctx.respond = false // Bypass Koa's built-in response handling
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })

  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

start()
